<?php
/*
 module:		用户管理
 create_time:	2022-04-13 18:58:25
 author:		
 contact:		
*/

namespace app\backend\controller;

use app\api\model\ZhAuthParent;
use app\backend\model\ZhMatchmaker as ZhMatchmakerModel;
use app\backend\model\ZhTopCard;
use app\backend\service\AuthService;
use app\backend\service\ExportService;
use app\backend\service\MemberService;
use app\backend\model\Member as MemberModel;
use app\backend\service\VipSysService;
use app\backend\model\ZhAuthentication;
use app\backend\service\ZhAuthenticationService;
use think\facade\App;
use think\facade\Db;
use think\facade\Filesystem;

class Member extends Admin
{


    /*首页数据列表*/
    function index()
    {
        
        if (!$this->request->isAjax()) {
            return view('index');
        } else {
            $limit  = $this->request->post('limit', 20, 'intval');
            $offset = $this->request->post('offset', 0, 'intval');
            $page   = floor($offset / $limit) + 1;

            $where                  = [];
            $where['nickname']      = $this->request->param('nickname', '', 'serach_in');
            $where['phone']         = $this->request->param('phone', '', 'serach_in');
            $where['status']        = $this->request->param('status', '', 'serach_in');
            $where['is_matchmaker'] = $this->request->param('is_matchmaker', '', 'serach_in');
            $where['is_vip']        = $this->request->param('is_vip', '', 'serach_in');
            $where['vip_number']    = $this->request->param('vip_number', '', 'serach_in');
            $where['wxapp_id']      = session('backend.wxapp_id');

            $order = $this->request->post('order', '', 'serach_in');    //排序字段 bootstrap-table 传入
            $sort  = $this->request->post('sort', '', 'serach_in');        //排序方式 desc 或 asc

            $field   = 'uid,p_id,matchmaker_id,nickname,avatar,balance,phone,pic,status,create_time,is_matchmaker,is_vip,auth_status,is_auth,s_desc,top_card_id,top_card_expiry,tags,pictures,age,height';
            $orderby = ($sort && $order) ? $sort . ' ' . $order : 'uid desc';

            $res = MemberService::indexList(formatWhere($where), $field, $orderby, $limit, $page);
            return json($res);
        }
    }

    //佳人绑定用户 验证当前佳人的红娘 和选择用户的红娘是否一致
    public function indexs()
    {
        $authentication_id = $this->request->get('authentication_id');
        $authentication    = ZhAuthentication::find($authentication_id);
        $matchmaker_id     = intval($authentication["matchmaker_id"]);
        if (!$this->request->isAjax()) {
            return view('index');
        } else {
            $limit  = $this->request->post('limit', 20, 'intval');
            $offset = $this->request->post('offset', 0, 'intval');
            $page   = floor($offset / $limit) + 1;

            $where             = [];
            $where['wxapp_id'] = session('backend.wxapp_id');
            $where2            = [];
            $where3            = [];
            $order             = $this->request->post('order', '', 'serach_in');    //排序字段 bootstrap-table 传入
            $sort              = $this->request->post('sort', '', 'serach_in');        //排序方式 desc 或 asc
            $field             = 'uid, nickname, phone,wxapp_id,matchmaker_id,real_name';
            //当前佳人绑定了红娘，绑定的用户对应红娘必须是当前佳人绑定的红娘，或者未绑定红娘的用户
            if ($matchmaker_id > 0) {
                $res = \app\backend\model\Member::where($where)->whereIn("matchmaker_id", [0, $matchmaker_id])->field($field)->order("uid desc")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
            } else {
                //当前佳人未绑定红娘，绑定的用户可以是任何用户
                $res = \app\backend\model\Member::where($where)->field($field)->order("uid desc")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
            }
            $res = ['rows' => $res['data'], 'total' => $res['total']];
            return json($res);
        }
    }

    /*修改排序开关按钮操作*/
    function updateExt()
    {
        $postField = 'uid,status,is_admin,sex';
        $data      = $this->request->only(explode(',', $postField), 'post', null);
        if (!$data['uid']) $this->error('参数错误');
        try {
            MemberModel::update($data);
        } catch (\Exception $e) {
            abort(config('my.error_log_code'), $e->getMessage());
        }
        return json(['status' => '00', 'msg' => '操作成功']);
    }

    /*查看详情*/
    function view()
    {
        $uid = $this->request->get('uid', '', 'serach_in');
        if (!$uid) $this->error('参数错误');
        $info          = MemberModel::find($uid);
        $matchmaker_id = intval($info->matchmaker_id);
        if ($matchmaker_id > 0) {
            $matchmaker = MemberModel::find($matchmaker_id);
            if ($matchmaker) {
                $info->matchmaker_id = $matchmaker->real_name;
            }
        } else {
            $info->matchmaker_id = "暂无";
        }
        $this->view->assign('info', $info);

        return view('view');
    }

    /**
     * @return \think\response\Json|\think\response\View
     * @author  lwx
     */
    function add()
    {
        if (!$this->request->isPost()) {
            return view('add');
        } else {
            $postField = 'pwd,uid,nickname,vip_number,avatar,create_time,status,balance,real_name,phone,is_auth,p_id,qr_code,is_admin,virtual_currency_balance,auth_status,s_desc,top_card_id,tags,pictures,age,height,certify_tags,recommend_tags';
            $data      = $this->request->only(explode(',', $postField), 'post', null);
            if(!empty($data["pwd"])){
                $data["pwd"]=md5($data["pwd"]);
            }
            if (!empty($data['top_card_id']) && $data['top_card_id'] > 0) {
                $card = ZhTopCard::find($data['top_card_id']);
                if (empty($card)) {
                    $this->error('置顶卡不存在');
                }
                if ($card['status'] == '0') {
                    $this->error('置顶卡未开启');
                }

                if (empty($card['day'])) {
                    $this->error('置顶卡天数错误');
                }
                $data['top_card_expiry'] = time() + 60 * 60 * 24 * $card['day'];
            }

            if (!empty($data['tags']) && count(explode(',', $data['tags'])) > 5) {
                $this->error('标签最多5个');
            }

            $res = MemberService::add($data);
            return json(['status' => '00', 'msg' => '添加成功']);
        }
    }

    /*修改*/
    function update()
    {
        if (!$this->request->isPost()) {
            $uid = $this->request->get('uid', '', 'serach_in');
            if (!$uid) $this->error('参数错误');
            $data = checkData(MemberModel::find($uid));

            $top_card_id = intval($data["top_card_id"]);
            if ($top_card_id > 0) {
                $card                  = ZhTopCard::find($top_card_id);
                $data["top_card_name"] = $card->name;
            }

            //查上级红娘
            if($data['matchmaker_id'] > 0){
                $tmp = \app\backend\model\ZhMatchmaker::find($data['matchmaker_id']);
                $data["top_member_name"] = $tmp['name'] . ' '. $tmp['phone'];
            }

            $this->view->assign('info', $data);
            return view('update');
        } else {
            $postField = 'pwd,price,uid,avatar,nickname,vip_number,avatar,create_time,status,balance,real_name,phone,is_auth,is_vip,p_id,qr_code,is_admin,is_matchmaker,matchmaker_id,virtual_currency_balance,auth_status,s_desc,top_card_id,tags,pictures,age,height,certify_tags,recommend_tags';
            $data      = $this->request->only(explode(',', $postField), 'post', null);
           //红娘id 修改了，同步到佳人表
            if(intval($data["matchmaker_id"])>0){
                $res =ZhAuthentication::where(["u_id"=>$data["uid"]])->save(["matchmaker_id"=>$data["matchmaker_id"]]);
            }

            /*      if ($data['auth_status'] == '2') {
                      $data['is_auth'] = 1;
              } else {
                      $data['is_auth'] = 0;
                  }*/

            if(!empty($data["pwd"])){
                //验证是不是和原来一样
                $member = checkData(MemberModel::find($data["uid"]));
                 if($member["pwd"]!= $data["pwd"] ){
                     $data["pwd"]=md5($data["pwd"]);
                 }
            }
            if (!empty($data['tags']) && count(explode(',', $data['tags'])) > 5) {
                $this->error('标签最多5个');
            }

            $memberInfo = MemberModel::find($data['uid']);
            if (!empty($data['top_card_id']) && $data['top_card_id'] != $memberInfo['top_card_id'] && $data['top_card_id'] > 0) {
                $card = ZhTopCard::find($data['top_card_id']);
                if (empty($card)) {
                    $this->error('置顶卡不存在');
                }
                if ($card['status'] == '0') {
                    $this->error('置顶卡未开启');
                }

                if (empty($card['day'])) {
                    $this->error('置顶卡天数错误');
                }
                $data['top_card_expiry'] = time() + 60 * 60 * 24 * $card['day'];
            }

            $res = MemberService::update($data);
            return json(['status' => '00', 'msg' => '修改成功']);
        }
    }


    function delete()
    {
        $idx = $this->request->post('uid', '', 'serach_in');
        if (!$idx) $this->error('参数错误');
        try {
            MemberModel::destroy(['uid' => explode(',', $idx)], true);
        } catch (\Exception $e) {
            abort(config('my.error_log_code'), $e->getMessage());
        }
        return json(['status' => '00', 'msg' => '操作成功']);
    }


    function import()
    {
        $file      = $this->request->file("file");
        $save_name = Filesystem::disk('public')->putFile('file/xls', $file);
        $data      = baseFromExcel('/' . App::getRootPath() . 'public/uploads/' . $save_name);

        $filedData = [
            '昵称'     => 'nickname',
            //'余额'     => 'balance',
            '真实姓名' => 'real_name',
            '标签'     => 'tags',
            '手机号'   => 'phone'
        ];
        $filedData2 = [
            '真实姓名'       => 'real_name',
            '性别'           => 'gender',
            '出生日期'       => 'date_birth',
            '年龄（虚岁）'   =>'age',
            '所在地'     => 'city',
            '身高（cm）'           => 'height',
            '爱情宣言'       => 'lova_declaration',
            '联系方式'       => 'contact_type',
            '手机号'         => 'contact',
            '体重（斤）'           => 'weight',
            '学历'           => 'education',
            '婚姻状况'       => 'marital_status',
            '有无子女'       => 'have_children',
            '民族'           => 'nation',
            '职业'           => 'occupation',
            '家庭情况'       => 'family_status',
            '月收入'         => 'income',
            '购房情况'       => 'purchase_status',
            '父母情况'        =>'parental_status',
            '购车情况'       => 'vehicle_status',
            '是否吸烟'       => 'is_smoking',
            '是否喝酒'       => 'is_drink',
            '所属红娘手机号' => 'matchmaker_id', // 需要将手机号转成id
            '属相'           => 'animal',
            '品貌'           => 'appearance',
            '信仰'           => 'belief',
            '年薪（万）'           => 'income',
            '父母状况'       => 'parental_status',
            '兄弟姐妹'       => 'sibling',
            '属相（冲）（宜）'         => 'zodiac_clash',
            '承诺'           => 'commitment',
            '联系人'         => 'contact',
            '联系人电话'=>'contacts',
            'MBTI'           => 'mbti',
            '星座'           => 'constellation',
            '资料标签'       => 'tags',
            '佳人备注'=>'notes',
            '是否党员'=>'is_party_member',
            '工作单位'=>'work',
            '征婚宣言'=>'lova_declaration',
            '择偶籍贯'=>'o_city',
            '择偶最小年龄'=>'o_min_age','择偶最大年龄'=>'o_max_age','择偶年龄' => 'o_age','择偶身高'   => 'o_height',
            '择偶所在地'     => 'o_city','择偶体重'=> 'o_weight', '择偶学历'=> 'o_education',
            '择偶婚况'       => 'o_marital_status','择偶年薪'=> 'o_income','择偶民族' => 'o_nation',
            '择偶购房情况'   => 'o_purchase_status', '择偶购车情况'   => 'o_vehicle_status',
            '择偶是否吸烟'   => 'o_is_smoking','择偶是否喝酒'   => 'o_is_drink',
            '择偶最小身高'=>'o_min_height', '择偶最大身高'=>'o_max_height',
            '择偶最小体重'=>'o_min_weight', '择偶最大体重'=>'o_max_weight',
            '择偶婚姻状况'=>'o_marital_status', '择偶有无小孩'=>'o_child', '其他要求'=>'o_other',
            '择偶民族'=>'o_nation', '你的理想型'=>'o_remarks',   '是否家长'=>'is_parent'
        ];

        $marital_status = [
            '未婚' => 1,
            '离异' => 2,
            '丧偶' => 3
        ];

        $have_children = [
            '无' => 1,
            '没有' => 1,
            '有'   => 2,
        ];

        $gender = [
            '男' => 1,
            '女' => 2,
        ];

        $purchase_status = [
            '已购房' => 2,
            '未购房'     => 1,
            '一套房' => 2,
            '两套房'       => 3,
            '三套及以上' => 4,
            '婚后买房'   => 5,
            '和家人同住' => 1,
            '租房' => 1
        ];
        // 1 10万以下、2 10-15万、3 16-20万、4 20万-50万、5 50万-100万、6 100万以上
        $income_status=[
            '10万以下'=>1,
            '10-15万'=>2,
            '16-20万'=>3,
            '20万-50万'=>4,
            '50万-100万'=>5,
            '100万以上'=>6

        ];
        $vehicle_status = [
            '已购车' => 2,
            '多辆车' => 3,
            '一辆车' => 2,
            '未购车' => 1,
        ];

        $is = [
            '是' => 2,
            '否' => 1,
        ];

        $newData_p=[];
        $newData2 = [];
        $exist    = [];



        foreach ($data as $row) {
            $newRow  = [];
            $newRow2 = [];
            /**
             * $row 的格式
             * Array
            (
            [昵称] => 测试昵称1
            [余额] => 1
            [真实姓名] => 张三
            [手机号] => 15261304594
            [出生日期] => 34322
            [身高] => 167
            [性别] => 男
            [爱情宣言] => 相貌好
            [标签] => 高富帅,有钱
            [所在地城市] => 天津市
            [体重] => 50
            [学历] => 硕士研究生
            [婚姻状况] => 未婚
            [有无子女] => 没有
            [民族] => 汉族
            [职业] => 设计师
            [家庭情况] => 父母弟弟
            [月收入] => 8000
            [购房情况] => 已购房
            [购车情况] => 未购车
            [是否抽烟] => 否
            [是否喝酒] => 否
            [择偶年龄] => 25,30
            [择偶身高] => 160175
            [择偶所在地] => 天津市
            [择偶体重] => 50,70
            [择偶学历] => 本科
            [择偶婚况] => 未婚
            [择偶月收入] => 8001-12000
            [择偶民族] => 汉族
            [择偶购房情况] => 已购房
            [择偶购车情况] => 未购车
            [择偶是否吸烟] => 否
            [择偶是否喝酒] => 否
            [我的理想型] => 活泼开朗
            [所属红娘手机号] => 15934485623
            [属相] =>
            [品貌] =>
            [信仰] =>
            [年薪] =>
            [父母状况] =>
            [兄弟姐妹] =>
            [属相冲] =>
            [承诺] =>
            [联系人] =>
            [MBTI] => 测试
            [星座] => 双子座
            [资料标签] => 高净值,经商
            )
             */
            foreach ($row as $key => $datum) {
                if ($this->in_data_array($key, $filedData)) {
                    $newRow[$filedData[$key]] = $datum === null ? '' : $datum;
                }
                if ($this->in_data_array($key, $filedData2)) {
                    $newRow2[$filedData2[$key]] = $datum === null ? '' : $datum;
                }
            }

            $newRow['createtime'] = time();
            $newRow['wxapp_id']   = session('backend.wxapp_id');

            // 红娘信息
            if ($newRow2['matchmaker_id']) {
                $matchmakerInfo = ZhMatchmakerModel::where('phone', $newRow2['matchmaker_id'])->find();
                if ($matchmakerInfo) {
                    $newRow2['matchmaker_id'] = $matchmakerInfo->matchmaker_id;
                } else {
                    $newRow2['matchmaker_id'] = 0;
                }
            } else {
                $newRow2['matchmaker_id'] = 0;
            }
//            var_dump($newRow['phone']);
//            exit();
            // 查找是否存在该用户
            //非空验证开始
            $check_res=$this->check_emp($newRow,$newRow2);
            if($check_res){
              //  return json(['status' => '00', 'msg' => 'null break..', 'exist' => $check_res]);
                continue;
            }
            //非空验证结束
            if(trim($newRow['phone'])!=""&&trim($newRow['phone'])!=" "){
                $memberInfo = MemberModel::where('phone', $newRow['phone'])->find();
            }
            if ($memberInfo) {//存在则跳过
                $newRow2['u_id'] = $memberInfo["uid"];
            } else {
                $res             = MemberModel::create($newRow);
                $newRow2['u_id'] = $res->uid;
            }
            // 查找资料有没有
            if ($newRow2['u_id']) {
                $authInfo = ZhAuthentication::where('u_id', $newRow2['u_id'])->find();
                if ($authInfo) {
                    $exist[] = $authInfo['authentication_id'];
                    continue;
                }
            }
            $newRow2['contact_type']      = '电话';
            $newRow2['gender']            = $gender[$newRow2['gender']];
            $newRow2['marital_status']    = $marital_status[$newRow2['marital_status']];
            $newRow2['have_children']     = $have_children[$newRow2['have_children']];
            $newRow2['purchase_status']   =intval( $purchase_status[$newRow2['purchase_status']]);
            $newRow2['vehicle_status']    = intval($vehicle_status[$newRow2['vehicle_status']]);
            $newRow2['income']            = $income_status[$newRow2['income']];
            $newRow2['is_smoking']        = $is[$newRow2['is_smoking']] ?? 0;
            $newRow2['is_drink']          = $is[$newRow2['is_drink']] ?? 0;
            $newRow2['o_marital_status']  = $marital_status[$newRow2['o_marital_status']] ?? 0;
            $newRow2['o_purchase_status'] = $purchase_status[$newRow2['o_purchase_status']] ?? 0;
            $newRow2['o_vehicle_status']  = $vehicle_status[$newRow2['o_vehicle_status']] ?? 0;
            $newRow2['o_is_smoking']      = $is[$newRow2['o_is_smoking']] ?? 0;
            $newRow2['o_is_drink']        = $is[$newRow2['o_is_drink']] ?? 0;
            $newRow2['createtime']        = time();
            $time                         = intval(($newRow2['date_birth'] - 25569) * 3600 * 24); //转换成1970年以来的秒数
            $newRow2['date_birth']        = gmdate('Y-m-d', $time);
            $newRow2['wxapp_id']          = session('backend.wxapp_id');
            if ($newRow2['is_parent']=="是") {
                $newData_p[]                   = $newRow2;
            }else{
                $newData2[]                   = $newRow2;
            }
        }
        if (!empty($newData2)) {
            ZhAuthentication::insertAll($newData2);
        }
        if (!empty($newData_p)) {
            ZhAuthParent::insertAll($newData_p);
        }
        return json(['status' => '00', 'msg' => '操作成功', 'exist' => $exist]);
    }

    //导入用户，验证字段是否存在空，存在的话返回true
    function check_emp($newRow,$newRow2){
        if(trim($newRow['nickname'])==""||trim($newRow['nickname'])==" "){
            return "nickname";
        }
        if(trim($newRow2['age'])==""||trim($newRow2['age'])==" "){
            return "age";
        }
        if(trim($newRow2['marital_status'])==""||trim($newRow2['marital_status'])==" "){
            return "marital_status";
        }
        if(trim($newRow2['city'])==""||trim($newRow2['city'])==" "){
            return "city";
        }
        if(trim($newRow2['animal'])==""||trim($newRow2['animal'])==" "){
            return "animal";
        }
        if(trim($newRow2['gender'])==""||trim($newRow2['gender'])==" "){
            return "gender";
        }
        if(trim($newRow2['height'])==""||trim($newRow2['height'])==" "){
            return "height";
        }
        if(trim($newRow2['weight'])==""||trim($newRow2['weight'])==" "){
            return "weight";
        }
        if(trim($newRow2['education'])==""||trim($newRow2['education'])==" "){
            return "education";
        }

        if(trim($newRow2['occupation'])==""||trim($newRow2['occupation'])==" "){

            return "occupation";
        }
        if(trim($newRow2['appearance'])==""||trim($newRow2['appearance'])==" "){
            return "appearance";
        }
        if(trim($newRow2['income'])==""||trim($newRow2['income'])==" "){
            return "income";
        }
        if(trim($newRow2['purchase_status'])==""||trim($newRow2['purchase_status'])==" "){
            return "purchase_status";
        }
        if(trim($newRow2['have_children'])==""||trim($newRow2['have_children'])==" "){
            return "have_children";
        }
        if(trim($newRow2['sibling'])==""||trim($newRow2['sibling'])==" "){
            return "sibling";
        }
        if(trim($newRow2['zodiac_clash'])==""||trim($newRow2['zodiac_clash'])==" "){
            return "zodiac_clash";
        }
        return false;
    }
    function in_data_array($key, $array)
    {
        foreach ($array as $k => $item) {
            if ($k == $key) {
                return true;
            }
        }
        return false;
    }

    function selectList()
    {
        return view('select_list');
    }

     // 导出
    public function export()
    {
        $expCellName = [
            'uid' => 'Id',
            'real_name' => '真实姓名',
            'balance'=>'余额',
            'phone'             => '手机号',
           /* 'mname'            => '上级红娘',*/
           'create_time'          => '注册时间',

            ];
        $export      = new ExportService();
        $spreadsheet = null;
        $sheet       = null;
        $limit   = 10000;
        $offset  = 0;
        $page    = floor($offset / $limit) + 1;
        $res = MemberModel::alias('a')->leftJoin('zh_matchmaker m', 'a.matchmaker_id=m.matchmaker_id')
            ->field(["a.uid"])->order("a.uid desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

        $total=$res["total"];

        if ($total == 0) {
            $this->error('导出数据为空');
        }
        $current_total = 0;     // 当前已循环条数
        $page_size     = 10000;
        $total_page    = intval(ceil($total / $page_size));

        for ($i = 0; $i < $total_page; $i++) {
            $page         = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;
            $res = MemberModel::alias('a')->leftJoin('zh_matchmaker m', 'a.matchmaker_id=m.matchmaker_id')
            ->field(["m.name mname","a.*"])->order("a.uid desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
            $list=$res["data"];
             foreach ($list as $key => &$val) {
                 $val['expires_time']=date("Y-m-d H:i:s",$val['expires_time']);
            }
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('用户数据-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page'          => $page,
                'page_size'     => 50000,      // 如果传了 current_total 则 page_size 就不用了
                'current_total' => $current_total,      // page_size 是 order 的，但是 newList 其实是 order_item 的
                'is_last_page'  => $is_last_page
            ]);
        }
    }

}

